package com.luoqy.speedy.modular.web.controller;


import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.luoqy.speedy.modular.web.aop.HttpAspect;
import com.luoqy.speedy.modular.web.service.WriteFictionService;
import com.luoqy.speedy.modular.web.utils.JsoupUtil;
import com.luoqy.speedy.modular.web.utils.Result;

/**
 * 抓取小说 控制器
 */
@Controller
@RequestMapping("sys")
public class FictionController {

    private static final Logger log = LoggerFactory.getLogger(HttpAspect.class);

    private final WriteFictionService writeFiction;

    @Autowired
    public FictionController(WriteFictionService writeFiction) {
        this.writeFiction = writeFiction;
    }


    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String index() {

        return "templates/fiction/sys";
    }

    /**
     * 单本小说增加
     * @param url
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "write", method = RequestMethod.POST)
    public Result fiction_write(@RequestParam("fiction_url") String url) {
        //boolean result = JsoupUtil.isConnection(url);
        try {
           if("success".equals(writeFiction.insertResult(url).get())){
        	   return new Result(200, "获取成功!");
           }else{
        	   return new Result(500, "获取失败:地址错误!");
           }
        } catch (Exception e) {
			// TODO: handle exception
        	return new Result(500, "获取失败:"+e.getMessage());
		}
        /*if (result) {    
        } else {
            log.info("FictionController/fiction_write:地址解析失败");
            return new Result(500, "小说地址解析失败,抓取失败!");
        }*/
    }

    /**
     * 单分类单页进行抓取增加小说
     * @param url 地址url
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "writes", method = RequestMethod.POST)
    public Result fiction_writes(@RequestParam("fiction_urls") String url) {
        //分类页面
	     boolean result = JsoupUtil.isConnection(url);
	     if (result) {
	    	 writeFiction.insert(url);
	    	 return new Result(200, "小说地址解析成功!");
        } else {
            log.info("FictionController/fiction_write:地址解析失败");
            return new Result(500, "小说地址解析失败,抓取失败!");
        }
    }
}